package org.spring.flower.student.message;

import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;

@Slf4j
@Component
public class MessageFanoutSender {

    @Resource
    private RabbitTemplate rabbitTemplate;
    @Value("${mq.config.exchange}")
    private String exchangeName;
    @Value("${mq.config.routeKey}")
    private String routeKey;

    /**
     * 百分百成功投递消息到MQ
     * 需要配置
     * publisher-confirm-type: correlated
     * publisher-returns: true
     */
    @PostConstruct
    public void setUp(){
        rabbitTemplate.setConfirmCallback((correlationData, ack, s) -> {
            if(!ack)
                return;
            try {
                log.info("接受确认的数据{}",correlationData.getId());
                log.info("保存本地消息ing......");
                log.info("保存本地消息成功!");
            } catch (Exception e) {
                log.error("保存本地消息异常");
            }

        });
    }


    public void sendMessage(){
        String msg_10086 = "我要给你发消息来测试[发送确认]";
        //rabbitTemplate.convertAndSend(exchangeName,"",msg);
        rabbitTemplate.convertAndSend(exchangeName,routeKey,msg_10086,new CorrelationData("10086"));
    }
}
